package com.wenda.admin.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wenda.admin.vo.BizCode;
import com.wenda.admin.vo.Resp;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/api/*",filterName = "apiFilter")
public class ApiFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession(false);
        ObjectMapper jsonMapper = ApplicationContextUtil.getBean(ObjectMapper.class);
        if(session == null){
            servletResponse.setCharacterEncoding("utf-8");
            servletResponse.setContentType("application/json;charset=UTF-8");
            servletResponse.getWriter().write(jsonMapper.writeValueAsString(Resp.error(BizCode.NOT_LOGIN)));
            return;
        }
        if(session.getAttribute("userKey") == null){
            servletResponse.setCharacterEncoding("utf-8");
            servletResponse.setContentType("application/json;charset=UTF-8");
            servletResponse.getWriter().write(jsonMapper.writeValueAsString(Resp.error(BizCode.NOT_LOGIN)));
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
}